<template>
  <div id="dataShareCreate" style="background-image: url('/static/background/background.png'); min-height: 99vh; position: relative;">
    <div id="tableContainer" style="position: absolute; top: 20px; left: 50%; transform: translateX(-50%);" align="center">
      <loading v-if="loading"></loading>
      <div id="dataShareCreate_information">数据共享平台</div>
      <div class="line"></div>
      <el-form :model="form" ref="form" :rules="rules" label-width="100px" id="form" class="demo-ruleForm" :inline="true">
        <el-form-item label="数据资源名称：" prop="dataResourceName" class="custom-label-color" :rules="[{validator: rules.dataResourceName, trigger:'blur', required: true}]">
          <el-input size="small" class="w300" placeholder="请输入数据资源名称"  v-model.trim="form.dataResourceName"></el-input>
        </el-form-item>
        <el-form-item label="数据类型：" prop='dataType' class=" custom-label-color"  :rules="[{ required: true, message: '请选择数据类型', trigger: 'change' }]">
          <el-select v-model='form.dataType' placeholder='请选择'
                     class="w300">
            <el-option v-for='item in typeList' :label='item.localName' :key='item.value' :value='item.value' ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据分类：" prop='dataCategory' class=" custom-label-color"  :rules="[{ required: true, message: '请选择数据分类', trigger: 'change' }]">
            <el-select v-model='form.dataCategory' placeholder='请选择'
                       class="w300">
            <el-option v-for='item in categoryList' :label='item.localName' :key='item.value' :value='item.value' ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据文件："  prop="dataAttachments"   class=" custom-label-color" >
          <el-upload
            class="upload-demo w300 " action="" :auto-upload=false accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpg,.png"
            :on-remove="handleRemove"
            :before-upload="dataHandlePreview"
            :on-change="dataHandlePreview"
            :file-list="dataAttachments">
            <el-button size="mini" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="证明文件：" prop="proofAttachments" class=" custom-label-color" >
          <el-upload
            class="upload-demo w300 " action="" :auto-upload=false accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpg,.png"
            :on-remove="handleRemove"
            :before-upload="proofHandlePreview"
            :on-change="proofHandlePreview"
            :file-list="proofAttachments">
            <el-button size="mini" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图片："prop="imageAttachments" class=" custom-label-color" >
          <el-upload
            class="upload-demo w300 " action="" :auto-upload=false accept=".jpg,.jpeg,.png"
            :on-remove="handleRemove"
            :before-upload="imageHandlePreview"
            :on-change="imageHandlePreview"
            :file-list="imageAttachments">
            <el-button size="mini" type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>

        <div style="margin-bottom: 30px;">
          <el-button style="margin-left: 10px;" size="small" type="primary" @click="updataClick">提交</el-button>
          <el-button style="margin-left: 10px;" size="small" @click="resetClick">返回</el-button>
        </div>
      </el-form>
    </div>

  </div>


</template>
<script>
// import getUserInfo from '@/api/login'
import parent from '@/public/parent.js'
import rules from '@/public/rules.js'
import request from '@/utils/request'

// 查字典
export function search(type) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/dataResource/dict/' + type,
    method: 'get'
  })
}

// 创建数据资源
export function createData(dataResourceName, userId, dataCategory, dataType, dataFiles) {
  return request({
    url: '/cloud/jcce/v1.0/kt1/dataResource',
    method: 'post',
    params: {
      dataResourceName: dataResourceName,
      userId: userId,
      dataType: dataType,
      dataCategory: dataCategory,
      proprietorshipStatus: 'PENDING'
    },
    data: dataFiles
  })
}
export default {
  name: 'dataShareCreate',
  mixins: [parent, rules],
  data() {
    // 定义校验规则
    const validateFileUrl = (rule, value, callback) => {
      if (this.dataAttachments.length < 1) { // 我控制了FileList 长度代表文件个数
        callback(new Error('请上传数据文件'))
      } else {
        callback()
      }
    }

    // eslint-disable-next-line no-unused-vars
    const validatePFileUrl = (rule, value, callback) => {
      if (this.proofAttachments.length < 1) { // 我控制了FileList 长度代表文件个数
        callback(new Error('请上传证明文件'))
      } else {
        callback()
      }
    }

    // eslint-disable-next-line no-unused-vars
    const validateIFileUrl = (rule, value, callback) => {
      if (this.imageAttachments.length < 1) { // 我控制了FileList 长度代表文件个数
        callback(new Error('请上传封面图片'))
      } else {
        callback()
      }
    }

    return {
      rules: {
        dataResourceName: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入数据资源名称'))
          } {
            callback()
          }
        },
        dataAttachments: [{ required: true, validator: validateFileUrl, trigger: 'change' }],
        proofAttachments: [{ required: true, validator: validatePFileUrl, trigger: 'change' }],
        imageAttachments: [{ required: true, validator: validateIFileUrl, trigger: 'change' }],
        password: (rule, value, callback) => {
          if (value === '') {
            callback(new Error('请输入密码'))
          } else {
            callback()
          }
        }
      },
      loading: false,
      dialogVisible: false,
      dataAttachments: [],
      proofAttachments: [],
      imageAttachments: [],
      form: {
        dataResourceName: '',
        proprietorshipStatus: 'PENDING',
        dataType: '',
        dataCategory: '',
        description: ''
      },
      categoryList: [],
      typeList: [],
      authorityList: []
    }
  },
  mounted() {
    this.getBaseDatas()
  },
  computed: {
    currentUser() {
      return this.$store.getters.user
    }
  },
  methods: {
    validateDataAttachments(rule, value, callback) {
      if (this.dataAttachments.length === 0) {
        callback(new Error('请上传数据文件'))
      } else {
        callback()
      }
    },
    handleRemove(file, fileList) {
    },
    imageHandlePreview(file, files) {
      if (!!file && file.size > 5 * 1024 * 1024) {
        this.$message({ showClose: true, message: this.$t('createVM.validate.file_size'), type: 'error' })
        files.pop()
      }
      this.imageAttachments = files
    },
    dataHandlePreview(file, files) {
      this.dataAttachments = files
    },
    proofHandlePreview(file, files) {
      if (!!file && file.size > 5 * 1024 * 1024) {
        this.$message({ showClose: true, message: this.$t('createVM.validate.file_size'), type: 'error' })
        files.pop()
      }
      this.proofAttachments = files
    },
    getBaseDatas() {
      // 分类
      search('category').then((data) => {
        this.categoryList = data.data
      }).catch((error) => {
        console.log(error)
      })
      // 类型
      search('type').then((data) => {
        this.typeList = data.data
      }).catch((error) => {
        console.log(error)
      })
      // 确权状态
      this.authorityList = [
        { id: '0', label: '全部', value: '' },
        { id: '1', label: '待确认', value: 'PENDING' },
        { id: '2', label: '确权中', value: 'CONFIRMING' },
        { id: '3', label: '已通过', value: 'APPROVED' },
        { id: '4', label: '驳回', value: 'REJECTED' }
      ]
    },
    // 保存 创建数据资源
    updataClick() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          var _self = this
          const dataFiles = new FormData()
          if (!!_self.dataAttachments && _self.dataAttachments.length > 0) {
            dataFiles.append('dataFile', _self.dataAttachments[0].raw)
          }

          // const proofFile = new FormData()
          if (!!_self.proofAttachments && _self.proofAttachments.length > 0) {
            dataFiles.append('proofFile', _self.proofAttachments[0].raw)
          }

          // const imageFile = new FormData()
          if (!!_self.imageAttachments && _self.imageAttachments.length > 0) {
            dataFiles.append('imageFile', _self.imageAttachments[0].raw)
          }

          createData(
            _self.form.dataResourceName,
            _self.currentUser['id'], // userId
            _self.form.dataCategory,
            _self.form.dataType,
            dataFiles).then(res => {
            // _self.mloading.hide()
            if (res.code === 0) {
              this.$message({
                message: '创建成功',
                type: 'success'
              })
              this.$router.push({ name: 'dataShare', params: { previousPage: 'pubCloud', routeLevel: 3 }})
            } else {
              this.$message({ showClose: true, message: error.msg, type: 'error' })
            }
          })
        }
      })
    },
    resetClick() {
      this.$router.push({ name: 'dataShare', params: { previousPage: 'pubCloud', routeLevel: 3 }})
    }
  },
  watch: {
    dataAttachments(nowval, oldval) {
      this.$refs['form'].validateField('dataAttachments');
    },
    imageAttachments(nowval, oldval) {
      this.$refs['form'].validateField('imageAttachments');
    },
    proofAttachments(nowval, oldval) {
      this.$refs['form'].validateField('proofAttachments');
    }
  }
}
</script>

<style lang="scss">
@import './css/dataShare.scss';
</style>
